import yaml, time
from pathlib import Path
from modules.camera import Camera
from modules.detector import Detector
from modules.recorder import Recorder
from modules.notifier import Notifier
import cv2
from modules.logger import get_logger
import logging

fmt = logging.Formatter(
    "[%(asctime)s.%(msecs)03d] %(name)s | %(levelname)s | %(message)s",
    datefmt="%H:%M:%S"
)

console = logging.StreamHandler()
console.setFormatter(fmt)

root = logging.getLogger()
root.setLevel(logging.INFO)
root.addHandler(console)



def main():
    logging.basicConfig(level=logging.INFO)
    log = get_logger("Main")
    log.info("===== 程序启动 =====")

    cfg = yaml.safe_load(open("config.yaml"))
    cam   = Camera(cfg["camera"])
    det   = Detector(cfg["detector"])
    rec   = Recorder(cfg["recorder"])
    notify= Notifier(cfg["notifier"])

    LAST_ALERT_TIME = 0  # 上次推送时间戳
    ALERT_COOLDOWN = cfg["detector"].get("alert_cooldown", 300)

    try:
        for frame in cam.frames():
            boxes, annotated = det(frame)

            now = time.time()
            if boxes:
                if now - LAST_ALERT_TIME >= ALERT_COOLDOWN:
                    LAST_ALERT_TIME = now  # 更新冷却起点
                    img_path = str(cam.out_dir / f"alert_{int(now)}.jpg")
                    cv2.imwrite(img_path, annotated)
                    rec.write("person_detected", img_path)
                    notify.send_wechat("罚单来袭", f"检测到 {len(boxes)} 名交警出现")
                    notify.send_wechat_image("罚单来袭", img_path)
                else:
                    log.debug("仍在冷却期，跳过推送")

            # 简单可视化（可选）
            # cv2.imshow("live", annotated)
            # if cv2.waitKey(1) == 27: break

    except KeyboardInterrupt:
        pass
    finally:
        log.info("===== 程序正常退出 =====")
        cv2.destroyAllWindows()

if __name__ == "__main__":
    main()